#include "MainFrame.h"
#include <wx/wx.h>
#include <wx/aboutdlg.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/filename.h>
#include <wx/treectrl.h>
#include <wx/icon.h>
#include <wx/imaglist.h>
#include "cJSON.h"
#include "raw_directory_tree_data.h"
#include "json_controller.h"

MainFrame::MainFrame(wxWindow* parent)
	: MainFrameBaseClass(parent)
{
	this->SetIcon(wxIcon(_T("appIcon")));
	
	wxImageList* treeImageList=new wxImageList(16, 16);
	treeImageList->Add(wxIcon(_T("treeFolderIcon")));
	treeImageList->Add(wxIcon(_T("treefileIcon")));
	raw_dir->AssignImageList(treeImageList);
	
	this->Connect(open_raw->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::OnOpenRaw), NULL, this);
}

MainFrame::~MainFrame()
{
}

void MainFrame::OnExit(wxCommandEvent& event)
{
	wxUnusedVar(event);
	clearAllJsons();
	Close();
}

void MainFrame::OnAbout(wxCommandEvent& event)
{
	wxUnusedVar(event);
	wxAboutDialogInfo info;
	info.SetCopyright(_("My MainFrame"));
	info.SetLicence(_("GPL v2 or later"));
	info.SetDescription(_("Short description goes here"));
	::wxAboutBox(info);
}

void MainFrame::OnOpenRaw(wxCommandEvent& event)
{
	wxUnusedVar(event);
	wxDirDialog openRawDialog(this, _T("Select the raw directory"), _T("/"), wxDD_NEW_DIR_BUTTON);
	if(openRawDialog.ShowModal()==wxID_OK)
	{
		wxTreeItemId rootId=raw_dir->AddRoot("raw", 0, -1, new RawDirectoryTreeData("raw",openRawDialog.GetPath(), -1));
		scanRawDirectory(rootId, openRawDialog.GetPath());
	}
}

void MainFrame::clearAllJsons()
{
	
}

void MainFrame::reloadAllJsons()
{
	
}

void MainFrame::saveAllJsons()
{
	
}

void MainFrame::scanRawDirectory(const wxTreeItemId& root, const wxString targetRaw)
{
	wxString fileSpec(_T("*"));
	int flags=wxDIR_FILES|wxDIR_DIRS;
	if(wxDir::Exists(targetRaw))
	{
		JSONController* jc=JSONController::getInstance(targetRaw);
		wxDir scanDir(targetRaw);
		if(scanDir.IsOpened())
		{
			wxString fileName;
			bool rtri=scanDir.GetFirst(&fileName, fileSpec, flags);
			while(rtri)
			{
				wxString fullFileName(targetRaw+"\\"+fileName);
				if(wxDir::Exists(fullFileName))
				{
					wxTreeItemId subBranch=raw_dir->AppendItem(root, fileName, 0, -1, new RawDirectoryTreeData(fileName, fullFileName, 0));
					scanRawDirectory(subBranch, fullFileName);
				}
				else
				{
					wxFileName fn(fullFileName);
					if(!fn.GetExt().IsSameAs(_T("bak"),true))
					{
						raw_dir->AppendItem(root, fileName, 1, -1, new RawDirectoryTreeData(fileName, fullFileName, 0));
					}					
				}
				rtri=scanDir.GetNext(&fileName);
			}
		}
	}	
}
